<?php


require_once 'ExceptionProcessor.php';
// Main APP
const COLOR_RESET = "\033[0m";
const COLOR_GREEN = "\033[32m";
const COLOR_YELLOW = "\033[33m";
const COLOR_BLUE = "\033[34m";
const COLOR_RED = "\033[31m";

function printColored($text, $color)
{
    if (function_exists('posix_isatty') && posix_isatty(STDOUT)) {
        echo $color . $text . COLOR_RESET . PHP_EOL;
    } else {
        echo $text . PHP_EOL;
    }
}

function StartServer($port, $numProcesses)
{
    try{
        echo "Starting $numProcesses servers..." . COLOR_GREEN;
        echo "\n" . "Servers Started! running on http://0.0.0.0:$port" . COLOR_GREEN . "\n";
        $command = "php -S localhost:$port -t ../public/App/source 2>&1 &";
        $processes = [];
        for ($i = 0; $i < $numProcesses; $i++) {
            $serverProcess = popen($command, 'r');

            if ($serverProcess === false) {
                die(COLOR_RED . "Failed to start server." . COLOR_RESET);
            }

            $processes[] = $serverProcess;
        }
        foreach ($processes as $process) {
            echo fread($process, 1024);
            pclose($process);
        }
    }catch (Exception $e) {
            $date = date("Y-m-d_H-i-s"); // 更改日期格式以避免文件名中的冒号
            new ExceptionProcessor($e->getMessage() . "$e\n", "CLI Err was happend!\n" . "turingframe.exception.cli\n" . "YukinaNetwork & BannerServer Tech Team ©2024\n" . "$date");
    }
}



$openfile = fopen("../config.json", "r");
global $result2;
if ($openfile) {
    $jsonContent = fread($openfile, filesize("../config.json"));
    fclose($openfile);
    $port = json_decode($jsonContent, true); // 解析为数组
    $result2 = $port['port'];
    $result3 = $port['thread-count'];
} else {
    echo "Failed to open file.";
}

StartServer($result2, $result3);
